nice_things/macros/var.macro.sh
var
Since 0.3.0 · Source
Synopsis#{{{ var <assignee>=<assignor> [<assignee>=<assignor>]… }}}
Configuration
–
Description
Use indirection to dynamically assign variables.
No validation checks are done at run-time, which makes the code printed by this macro much faster than invoking the assign_variable function, but unsafe to use on untrusted inputs.
Three forms of <assignee> can be used:
- mandatory: The default; simply use the name of a variable or positional parameter as
<assignee>. Will abort at run-time if<assignee>is null. - optional: Append a question mark
?to the<assignee>name:<assignee>?=<assignor>; Will do nothing if<assignee>is null at run-time. - explicit: Write your own parameter expansion in the
<assignee>position, implementing whatever rules you want. For advanced use-cases, like dynamic buckets in a data structure.
Options
–
Operands
<assignee>: Variable or positional parameter containing the name of the variable to be assigned.<assignor>: Variable or positional parameter holding the value to assign.
Stdin
–
Stdout
One line of code is printed.
Stderr
–
Exit status0: Successful completion.
Abort
Aborts if <assignee> is null.
Usage examples
# Assign the result of a function to the <out_var> parameter
#{{{
var 1=result
#}}}
# Assign the result of a function to an optional <out_var> parameter
#{{{
var '1?=result'
#}}}
# Example taken from Array_bucket_set_
# Assign values to arbitrary variable name expansions
#{{{
# shellcheck disable=SC2016
var 'NS__bucket_${1:?}__${2:?}=${3}' \
'NS__bucket_${1}__${2}_len=${4}'
#}}}